package com.example.flink.aggregation;

import com.example.flink.model.WaterModel;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created with IntelliJ IDEA.
 * ClassName: KeyByStream
 * Package: com.example.flink.aggregation
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-20
 * Time: 21:20
 */

//聚合算子之前 都要keyBy分组 从逻辑上划分不同的key
public class KeyByStream {
    public static void main(String[] args) throws Exception {
        //简单聚合算子也是如此

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        //对象输入式 SingleOutputStreamOperator
        SingleOutputStreamOperator<WaterModel> map = env.readTextFile("./pojo.txt")
                //这里用到转换算子 将输入的字符串 封装转换为对象
                .map(new MapFunction<String, WaterModel>() {
                    @Override
                    public WaterModel map(String value) throws Exception {
                        String[] s = value.split(" ");
                        WaterModel waterModel = new WaterModel(s[0], Long.valueOf(s[1]), Integer.valueOf(s[2]));
                        return waterModel;
                    }
                });

        //使用KeyBy 将相同的id数据分为一组
        map.keyBy(new KeySelector<WaterModel, String>() {
            @Override
            public String getKey(WaterModel value) throws Exception {
                return value.getId();
            }
            //reduce规约聚合 最聚合计算 输入数类型 = 输入输出类型 在keyby之后使用
            //转换算子 filter也是 一样的
        }).reduce(new ReduceFunction<WaterModel>() {
            @Override
            public WaterModel reduce(WaterModel value1, WaterModel value2) throws Exception {
                return new WaterModel(value1.getId(), value1.getTs()+value2.getTs(), value1.getVc() + value2.getVc());
            }
        }).print();

        env.execute();

    }
}
